﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using Framework.Library.Base.Base;
using Framework.Library.Base.DataAccess;
using Framework.Library.Base.Extensions;
using Framework.Library.Core.Config;
using Framework.Library.Core.Utils;
using Framework.Library.Data.DAL;
using Framework.Library.Data.DAO;
using Framework.Library.Data.DAL.JObject;

namespace Framework.Portal.Layouts.Admin.Components.Teenio.Workflow
{
    public partial class ArchiveList : BaseControl
    {
        private static TeenioPermission curPermision = new TeenioPermission();
        private readonly string MENUNAME = string.Empty;
        private int _curPage;

        public ArchiveList()
        {
        }

        public ArchiveList(JSection section)
        {
            MENUNAME = section.title;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            drpContentType.DataSource = StaticData.ArticleType;
            drpContentRank.DataSource = StaticData.ArticleRank;
            drpContentType.DataBind();
            drpContentRank.DataBind();
            drpContentType.Items.Insert(0, new ListItem("All", "0"));
            drpContentRank.Items.Insert(0, new ListItem("All", "0"));
            if (!Page.IsPostBack)
            {
                curPermision = ManagerFactory.TeenioPermissionManager.GetPermision(currentUserId,
                                                                                    Session.WorkingPortal().PORTALID);
                LoadMenus();
                lblCommandName.Text = MENUNAME;
                //23/02/2011
                txtFromDate.Text = DateTime.Now.AddDays(-21).ToString("dd/MM/yyyy");
                txtToDate.Text = DateTime.Now.AddDays(1).ToString("dd/MM/yyyy");
                LoadData(_curPage);
            }
        }

        private void LoadMenus()
        {
            List<PortalMenu> dt = ManagerFactory.PortalMenuManager.GetAll(Session.WorkingPortal().PORTALID);
            if (dt != null)
            {
                PortalAccess.LoadMenus(dt, dropZones.Items);
                if (curPermision != null)
                {
                    if (!string.IsNullOrEmpty(curPermision.ZONES))
                    {
                        string permisionZoneCollection = curPermision.ZONES;
                        if (!string.IsNullOrEmpty(permisionZoneCollection))
                        {
                            int i = 0;
                            while (i < dropZones.Items.Count)
                            {
                                if (permisionZoneCollection.IndexOf("|" + dropZones.Items[i].Value + "|") < 0)
                                    dropZones.Items.RemoveAt(i);
                                else
                                    i += 1;
                            }
                        }
                    }
                    else
                        dropZones.Items.Clear();
                }
            }
            dropZones.Items.Insert(0, new ListItem("Root", "0"));
        }

        private void LoadData(int page)
        {
            string zoneId = dropZones.SelectedValue;
            if (zoneId == "0")
            {
                if (curPermision != null)
                {
                    if (!string.IsNullOrEmpty(curPermision.ZONES))
                    {
                        curPermision.ZONES = curPermision.ZONES.Remove(0, 1);
                        curPermision.ZONES = curPermision.ZONES.Remove(curPermision.ZONES.Length - 1, 1);
                        zoneId = curPermision.ZONES.Replace('|', ',');
                    }
                }
            }
            string contentType = drpContentRank.SelectedValue;
            if (contentType == "0")
            {
                string _contentType = string.Empty;
                foreach (var c in StaticData.ArticleRank)
                {
                    _contentType += c.Key + ",";
                }
                contentType = _contentType.TrimEnd(',');
            }
            string search = txtkeysearch.Text;
            if (string.IsNullOrEmpty(search))
                search = "%%";
            else
                search = "%" + search + "%";
            DateTime fromDate = DateTime.MinValue;
            DateTime toDate = DateTime.MaxValue;
            if (!string.IsNullOrEmpty(txtFromDate.Text))
            {
                if (!string.IsNullOrEmpty(txtToDate.Text))
                {
                    fromDate = DateTime.ParseExact(txtFromDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    toDate = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                }
                else
                    fromDate = DateTime.ParseExact(txtFromDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }
            //ManagerFactory.GetCMSDistributionManager.PurgeData();
            //List<TeenioContent> dtSearch = ManagerFactory.TeenioContentManager.Content_Search(zoneId, Session.GetUser().USERID,
            //                                                                            search, Session.WorkingPortal().PORTALID,
            //                                                                            fromDate, toDate, contentType,
            //                                                                            (int) CMSWorkFlow.Archive);
            List<TeenioContent> dtSearch = new List<TeenioContent>();
            if (dtSearch != null)
            {
                rptDistributed.DataSource = dtSearch;
                rptDistributed.DataBind();

                //dtgDeployList.DataSource = dtSearch;
                //dtgDeployList.PageIndex = page;
                //dtgDeployList.PageSize = 20;
                //dtgDeployList.DataBind();
            }
            else
            {
                rptDistributed.DataSource = null;
                rptDistributed.DataBind();
            }
            //Pager.Count = 1000;// dtgDeployList.Rows.Count;
            //Pager.PageSize = 10;
            //Pager.CurrentPageIndex = 1;
        }

        protected void rptDistributed_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var curData = (TeenioContent)e.Item.DataItem;
                var hplContent = (HyperLink) e.Item.FindControl("hplContent");
                var drpRPTRANK = (DropDownList) e.Item.FindControl("drpRPTRANK");
                var lblKey = (HiddenField) e.Item.FindControl("lblKey");
                lblKey.Value = curData.CONTENT_ID.ToString();
                drpRPTRANK.DataSource = StaticData.ArticleRank;
                drpRPTRANK.DataBind();
                drpRPTRANK.SelectedValue = curData.CONTENT_RANK.ToString();
                hplContent.Text = curData.CONTENT_HEADLINE;
                hplContent.NavigateUrl = Request.RawUrl + "&t=1&a=" + curData.CONTENT_ID;
            }
        }

        protected void rptDistributed_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            int xID = ConvertUtility.ToInt32(e.CommandArgument);
            switch (e.CommandName)
            {
                case "edit":
                    Response.Redirect(Request.RawUrl + "&t=1&a=" + xID, true);
                    break;
                case "unpublish":
                    ManagerFactory.DAOEntity.Update(new TeenioContent
                                                                {
                                                                    CONTENT_ID = xID,
                                                                    CONTENT_STATUS = (int) CMSWorkFlow.Archive
                                                                });
                    lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
                    LoadData(_curPage);
                    break;
                default:
                    break;
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData(_curPage);
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem items in rptDistributed.Items)
            {
                var chkCheckThis = (CheckBox) items.FindControl("chkCheckThis");
                if (chkCheckThis.Checked)
                {
                    string strTemp = ((HiddenField) items.FindControl("lblKey")).Value;
                    var drpRPTRANK = (DropDownList) items.FindControl("drpRPTRANK");
                    ManagerFactory.DAOEntity.Update(new TeenioContent
                                                                {
                                                                    CONTENT_ID = Convert.ToInt32(strTemp),
                                                                    CONTENT_RANK =
                                                                        Convert.ToInt32(drpRPTRANK.SelectedValue)
                                                                });
                }
            }
            lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
        }
    }
}